<?php

namespace app\home\controller;

// 引入公共控制器
use app\common\controller\Home;

class Subject extends Home
{

    protected $noNeedLogin = ['index', 'info'];

    public function _initialize()
    {
        // 调用父类构造函数
        parent::_initialize();

        $this->BusinessModel = model('Business.Business');
        $this->SubjectModel = model('Subject.Subject');
        $this->ChapterModel = model('Subject.Chapter');
        $this->CollectionModel = model('Business.Collection');
        $this->CouponReceiveModel = model('Coupon.Receive');
        $this->OrderModel = model('Subject.Order');
        $this->RecordModel = model('Business.Record');
        $this->CommissionModel = model('Business.Commission');
        $this->CommentModel = model('Subject.Comment');
        $this->PayModel = model('Pay.Pay');
    }

    // 课程首页
    public function index()
    {
        if ($this->request->isPost()) {
            // 获取页码
            $page = $this->request->param('page', 1, 'intval');

            // 获取搜索关键字
            $keywords = $this->request->param('keywords', '', 'trim');
            // 教师ID
            $teacherid = $this->request->param('teacherid', 0, 'intval');

            $where = [];

            if ($teacherid) {
                $where['teacherid'] = $teacherid;
            }

            if ($keywords) {
                $where['title'] = ['like', "%{$keywords}%"];
            }

            // 每页显示数量
            $limit = 10;
            // 计算偏移量
            $offset = ($page - 1) * $limit;

            // 组装响应数据
            $data = [
                'list' => [],
                'count' => 0,
            ];

            // 查询课程列表
            $subjectList = $this->SubjectModel
                ->where($where)
                ->limit($offset, $limit)
                ->with(['category', 'teacher'])
                ->order('id desc')
                ->select();

            // 组装数据
            if ($subjectList) {
                $data['list'] = $subjectList;
                $data['count'] = $this->SubjectModel->count();


                // 响应数据
                $this->success('', '', $data);
            } else {
                // 响应数据
                $this->error('暂无数据', '', $data);
            }
        }

        return $this->view->fetch();
    }

    // 课程详情
    public function info()
    {
        // 获取课程ID
        $subid = $this->request->param('subid', 0, 'trim');

        $info = $this->SubjectModel
            ->with(['category', 'teacher'])
            ->find($subid);

        if (!$info) {
            $this->error('该课程不存在');
            exit;
        }

        // 是否点赞
        $info['likes_active'] = false;
        // 是否收藏
        $info['collection_active'] = false;
        // 是否购买
        $info['order_active'] = false;

        // 获取用户信息
        $Business = $this->IsLogin(false);

        if ($Business) {
            // 查询课程是否点赞
            $likes = isset($info['likes']) ? trim($info['likes']) : '';
            $likes = explode(',', $likes);
            $info['likes_active'] = in_array($Business['id'], $likes) ? true : false;

            // 查询课程是否收藏
            $collection = $this->CollectionModel->where(['busid' => $Business['id'], 'status' => 'subject', 'collectid' => $subid])->find();
            $info['collection_active'] =  $collection ? true : false;

            // 查询是否已购买该课程
            $order = $this->OrderModel->where(['busid' => $Business['id'], 'subid' => $subid])->find();
            $info['order_active'] = $order ? true : false;
        }

        // 查询课程章节
        $chapterList = $this->ChapterModel->where('subid', $subid)->select();

        // 章节总数
        $info['chapter'] = count($chapterList);

        // 查询课程评价信息
        $comment = $this->CommentModel->with([
            'business'
        ])->where([
            'busid' => $Business['id'],
            'subid' => $subid,
        ])->select();
        $info['commentList'] = $comment;

        // var_dump($Business['id']);
        // var_dump($subid);
        // var_dump($comment);
        // exit;

        $this->assign([
            'info' => $info,
            'chapterList' => $chapterList,
        ]);

        return $this->view->fetch();
    }

    // 课程点赞
    public function likes()
    {
        $subid = $this->request->param('subid', 0, 'trim');

        $info = $this->SubjectModel
            ->find($subid);

        if (!$info) {
            $this->error('该课程不存在');
            exit;
        }

        // 获取课程点赞列表
        $likes = isset($info['likes']) ? trim($info['likes']) : '';
        $likes = explode(',', $likes);

        if (in_array($this->Business['id'], $likes)) {
            $key = array_search($this->Business['id'], $likes);
            unset($likes[$key]);
            $likes = array_filter($likes);

            $data = [
                'id' => $subid,
                'likes' => implode(',', $likes)
            ];

            $result = $this->SubjectModel->isUpdate(true)->save($data);
            if ($result === false) {
                $this->error($this->error('取消点赞失败：' . $this->SubjectModel->getError()));
                exit;
            } else {
                $this->success('取消点赞成功');
            }
        } else { // 未点赞
            $likes[] = $this->Business['id'];
            $likes = array_filter($likes);

            $data = [
                'id' => $subid,
                'likes' => implode(',', $likes)
            ];

            $result = $this->SubjectModel->isUpdate(true)->save($data);

            if ($result === false) {
                $this->error($this->error('点赞失败：' . $this->SubjectModel->getError()));
                exit;
            } else {
                $this->success('点赞成功');
            }
        }
    }

    // 课程收藏
    public function collection()
    {
        $subid = $this->request->param('subid', 0, 'trim');

        $info = $this->SubjectModel
            ->find($subid);

        if (!$info) {
            $this->error('该课程不存在');
            exit;
        }

        // 获取课程收藏列表
        $collection = $this->CollectionModel->where([
            'busid' => $this->Business['id'],
            'status' => 'subject',
            'collectid' => $subid
        ])->find();

        if ($collection) {
            // 取消收藏,删除记录
            $result = $this->CollectionModel->where(['id' => $collection['id']])->delete();
            if ($result === false) {
                $this->error($this->error('取消收藏失败：' . $this->CollectionModel->getError()));
                exit;
            } else {
                $this->success('取消收藏成功');
            }
        } else { // 未收藏
            $result = $this->CollectionModel->insert([
                'busid' => $this->Business['id'],
                'status' => 'subject',
                'collectid' => $subid,
                'createtime' => time(),
            ]);

            if ($result === false) {
                $this->error($this->error('收藏失败：' . $this->CollectionModel->getError()));
                exit;
            } else {
                $this->success('收藏成功');
            }
        }
    }

    // 确认订单
    public function confirm()
    {
        // 获取课程ID
        $subid = $this->request->param('subid', 0, 'trim');

        // 获取课程信息
        $info = $this->SubjectModel->with(['category', 'teacher'])->find($subid);

        if (!$info) {
            $this->error('课程不存在');
            exit;
        }

        // 获取优惠券列表
        $couponlist =  $this->CouponReceiveModel->with('coupon')->where(['busid' => $this->Business['id'], 'receive.status' => '1'])->select();

        $this->assign([
            'info' => $info,
            'couponlist' => json_encode($couponlist)
        ]);

        if ($this->request->isPost()) {
            // 获取优惠券ID
            $couponid = $this->request->param('coupon', 0, 'trim');
            // 支付方式
            $pay = $this->request->param('pay', 'money', 'trim');

            //总价
            $total = isset($info['price']) ? $info['price'] : 0;

            //查询是否有选择优惠券
            $coupon = $this->CouponReceiveModel->with('coupon')->where(['receive.status' => '1'])->find($couponid);

            if ($coupon) {
                //获取折扣率
                $rate = isset($coupon['coupon']['rate']) ? $coupon['coupon']['rate'] : 1;

                // 总优惠券价
                $total = bcmul($total, $rate, 2);
            }

            // 余额支付
            if ($pay == "money") {
                /*
                    课程订单表  新增
                    用户表余额  更新
                    用户消费记录表 新增
                    优惠券领取表  更新
                    客户佣金表 新增
                */
                // 开启事务
                $this->OrderModel->startTrans();
                $this->BusinessModel->startTrans();
                $this->RecordModel->startTrans();
                $this->CouponReceiveModel->startTrans();
                $this->CommissionModel->startTrans();

                // 组装新增订单信息
                $OrderData = [
                    'subid' => $subid,
                    'busid' => $this->Business['id'],
                    'total' => $total,
                    'code' => build_code('SUB'),
                    'pay' => $pay
                ];

                // 新增订单表记录
                $OrderStatus = $this->OrderModel->save($OrderData);

                if ($OrderStatus === false) {
                    $this->error($this->OrderModel->getError());
                    exit;
                }

                // 剩余余额
                $money = bcsub($this->Business['money'], $total, 2);

                // 组装更新用户余额信息
                $BusinessData = [
                    'id' => $this->Business['id'],
                    'money' => $money
                ];

                // 验证器
                $validate = [
                    [
                        'money' => ['number', 'egt:0'],
                    ],
                    [
                        'money.number'  => '余额必须是数字类型',
                        'money.egt'      => '余额不足请先充值',
                    ]
                ];

                // 更新用户余额
                $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

                // 更新用户余额失败
                if ($BusinessStatus === false) {
                    // 回滚订单表
                    $this->OrderModel->rollback();
                    $this->error($this->BusinessModel->getError());
                    exit;
                }

                // 组装新增用户消费记录信息
                $RecordData = [
                    'total' => $total,
                    'busid' => $this->Business['id'],
                    'content' => "购买了[{$info['title']}]课程,花费了￥{$total}元"
                ];

                // 新增用户消费记录表记录
                $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);
                if ($RecordStatus === false) {
                    // 回滚事务
                    $this->OrderModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->error($this->RecordModel->getError());
                    exit;
                }

                //如果有选择优惠券那么就要更新优惠券使用状态
                if ($coupon) {
                    // 组装更新优惠券领取表信息
                    $CouponReceiveData = [
                        'id' => $couponid,
                        'status' => '0'
                    ];

                    // 更新优惠券领取表记录
                    $CouponReceiveStatus =  $this->CouponReceiveModel->isUpdate(true)->save($CouponReceiveData);
                    if ($CouponReceiveStatus === false) {
                        // 回滚事务
                        $this->OrderModel->rollback();
                        $this->BusinessModel->rollback();
                        $this->RecordModel->rollback();
                        $this->error($this->CouponReceiveModel->getError());
                        exit;
                    }
                }

                // 推荐人佣金
                // 获取推荐人信息
                $parentid = isset($this->Business['parentid']) ? trim($this->Business['parentid']) : 0;
                $parent = $this->BusinessModel->find($parentid);

                if ($parent) {
                    // 组装用户佣金表记录
                    $CommissionData = [
                        'orderid' => $this->OrderModel->id,   //获取插入最后一条的自增ID
                        'busid' => $this->Business['id'],
                        'parentid' => $parentid,
                        'amount' => bcmul($total, config('site.AmountRate'), 2),
                        'type' => 'subject',
                        'status' => '0'
                    ];

                    // 新增用户佣金表记录
                    $CommissionStatus = $this->CommissionModel->save($CommissionData);
                    if ($CommissionStatus === false) {
                        $this->OrderModel->rollback();
                        $this->BusinessModel->rollback();
                        $this->RecordModel->rollback();
                        $this->CouponReceiveModel->rollback();
                        $this->error($this->CommissionModel->getError());
                        exit;
                    }
                }


                if ($OrderStatus === false || $BusinessStatus === false || $RecordStatus === false) {
                    $this->OrderModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->CouponReceiveModel->rollback();
                    $this->CommissionModel->rollback();
                    $this->error('购买课程失败');
                    exit;
                } else {
                    $this->OrderModel->commit();
                    $this->BusinessModel->commit();
                    $this->RecordModel->commit();
                    $this->CouponReceiveModel->commit();
                    $this->CommissionModel->commit();
                    $this->success('购买课程成功', 'home/business/subject');
                    exit;
                }
            } else {

                // 携带一个自定义的参数过去
                $third = [
                    'busid' => $this->Business['id'],
                    'subid' => $subid,
                    'couid' => $couponid
                ];

                //开始调用支付(组装参数)
                $data = [
                    'name' => '课程购买', //标题
                    'third' => $third, //传递的第三方的参数
                    'type' => $pay, //支付方式
                    'total' => $total, //订单原价充值的价格 
                    'cashier' => 1, //是否需要收银台界面
                    'jump' => "/home/subject/info?subid=$subid&action=success", //订单支付完成后跳转的界面
                    'notice' => '/home/pay/subject', //异步回调地址
                ];

                //调用模型中的支付方法
                $result = $this->PayModel->payment($data);

                echo $result;
                exit;
            }
        }

        return $this->view->fetch();
    }

    // 播放
    public function play()
    {
        // 获取课程ID
        $subid = $this->request->param('subid', 0, 'trim');
        // 获取章节ID
        $chpaterid = $this->request->param('chpaterid', 0, 'trim');

        // 获取课程信息
        $info = $this->SubjectModel->find($subid);

        if (!$info) {
            $this->error('课程不存在');
            exit;
        }

        // 获取订单信息(确认是否已购买课程)
        $orderinfo = $this->OrderModel->where(['subid' => $subid, 'busid' => $this->Business['id']])->find();
        if (!$orderinfo) {
            $this->error('请先购买课程');
            exit;
        }

        // 组装查询章节信息条件
        $where = [
            'subid' => $subid
        ];

        if ($chpaterid) {
            $where['id'] = $chpaterid;
        }

        // 查询章节信息
        $chpater = $this->ChapterModel->where($where)->find();

        $this->success('查询成功', '', $chpater);
    }

    // 评论
    public function comment()
    {
        if ($this->request->isPost()) {

            // 获取课程id
            $subid = $this->request->param('subid', 0, 'trim');
            // 获取页码
            $page = $this->request->param('page', 1, 'trim');
            // 每页显示数量
            $limit = 10;
            // 计算偏移量
            $offset = ($page - 1) * $limit;

            // 获取查询关键词
            $keywords = $this->request->param('keywords', '', 'trim');

            $where = [];
            // 组装查询条件
            if (!empty($keywords)) {
                $where['fa_subject_comment.content'] = ['like', "%$keywords%"];
            }

            $where['subid'] = $subid;
            // 查询评论表全部信息
            $commentList = $this->CommentModel->with([
                'business',
                'subject'
            ])->where($where)->limit($offset, $limit)->order('rate')->select();


            if ($commentList) {
                // 组装数据
                $data['list'] = $commentList;
                $data['count'] = $this->CommentModel->where($where)->count();

                // 响应数据
                $this->success('', '', $data);
            } else {
                $this->error('暂无数据', '');
            }

            // 赋值变量
            $this->assign('commentList', $commentList);
        }

        return $this->view->fetch();
    }
}
